package com.kylin.common.taglib;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Random;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.apache.log4j.Logger;
import org.apache.struts.Globals;

import com.kylin.common.exception.BusinessException;
import com.kylin.common.util.MemObjFactory;
import com.kylin.hibernate.BaseHibernateDAO;
import com.kylin.module.ad.business.ADBlogic;
import com.kylin.module.ad.orm.AD;
import com.kylin.module.ad.orm.ADType;

/**
 * 广告文件的保存目录在 /AD/
 * <mytag:AD type="home-top" index="2" language="zh-cn" />
 * @author ly
 *
 */
public class ADTag  extends BodyTagSupport {
	protected static Logger log = Logger.getLogger(ADTag.class);
	/** 广告类别 */
	protected String type;
	/** 宽度 */
	protected String width;
	/** 高度 */
	protected String height;
	/** 广告顺序标号 */
	protected String index;
	
	/** 所属语言 */
	protected String language;

	/*  
	 *  
	 * @return
	 * @throws JspException
	 */
	public int doStartTag() throws JspException {
		//if (language == null || language.equals("")){
			Locale loc = (Locale) pageContext.getAttribute(org.apache.struts.Globals.LOCALE_KEY, pageContext.SESSION_SCOPE);
			if(loc != null)
				language = loc.toString();
			else
			    language = "zh_CN";
		//}
		log.debug("广告语言("+index+")= "+language);
		ADType adType = null;
		try {
			adType = MemObjFactory.getADType(type,language);
			if(adType == null ){
				log.error("没有标识符为 "+type+" 的广告类型");
				List l =new ArrayList(MemObjFactory.ADs.keySet());
				if(l!=null)
				for(int i=0;i<l.size();i++){
					Object k = l.get(i); 
					System.out.print("\n ADS:"+k);
					System.out.print(","+MemObjFactory.ADs.get(k) +"\n");
				}
				outputDefaultImg("");
				return SKIP_BODY;
			}
			if (width == null && adType.getWidth() != null)
				width = adType.getWidth() + "";
			if (height == null && adType.getHeight()!=null)
				height = adType.getHeight() + "";
			if(adType.getAdList() == null || adType.getAdList().size() < 1){
				log.error("要显示的广告位还没有登记广告 has not the AD for("+language+")");
				outputDefaultImg(adType.getMark());
				return SKIP_BODY;
			}
			int orderNum = getIndexNumber(adType,adType.getAdList().size(),index);
			System.out.println("\n-------orderNum="+orderNum);
			AD ADobj = (AD)adType.getAdList().get(orderNum-1);
			String ext = "";
			int idx = ADobj.getFileurl().lastIndexOf(".");
			if (idx > 0 && idx < ADobj.getFileurl().length()) {
				ext = ADobj.getFileurl().substring(idx);
			}
			if ("swf".equals(ext)) {
				outputFlash(ADobj);
			} else {
				outputImg(ADobj);
			}
			if(ADobj != null){
				if(ADobj.getHits()==null)
					ADobj.setHits(new Integer(1));
				else
					ADobj.setHits(new Integer(ADobj.getHits().intValue() + 1));
			}
			BaseHibernateDAO.update(ADobj);
		}catch(NumberFormatException e){
			try {
				if(adType != null)
					outputDefaultImg("");
				else
					outputDefaultImg(adType.getMark());
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return SKIP_BODY;
	}

	/**
	 * 取得本次显示广告的序号
	 * 有的滚动广告是需要随即或者变换顺序的
	 * @param adType
	 * @param size
	 * @param index
	 * @return
	 */
	private int getIndexNumber(ADType adType,int size,String index){
		int indexNumber = 1;
		if(index != null)
			indexNumber = Integer.parseInt(index);
		if(ADType.SHOWTYPE_ROLL.equals(adType.getShowtype()) ){
			log.debug("---------------滚动广告");
			if(pageContext.getAttribute(adType.getMark()+"ADIndexNumber", pageContext.SESSION_SCOPE) instanceof Integer)
				indexNumber = ((Integer)pageContext.getAttribute(adType.getMark()+"ADIndexNumber", pageContext.SESSION_SCOPE)).intValue();
			else{
				try{
				Random r = new Random(size);
				indexNumber = r.nextInt();
				}catch(Exception e){
					log.error("选择滚动广告("+adType.getMark()+")的起始号错误",e);
				}
			}
			
		}else{
			log.debug("-------------固定广告");
		}
		if(indexNumber > size || indexNumber <1){		
			throw new NumberFormatException("此位置广告只有 1 到 "+size);
		}
		pageContext.setAttribute(adType.getMark()+"ADIndexNumber", new Integer(indexNumber+1), pageContext.SESSION_SCOPE);

		return indexNumber;
	}
	private void outputFlash(AD ad) throws IOException, BusinessException{
		StringBuffer sb = new StringBuffer();
		String filePath = "/AD/"+ ad.getAdtype().getMark()+"/"+ad.getFileurl();
		sb.append("<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000'        ");
		sb.append("   codebase='http://download.macromedia.com/pub/");
		sb.append("shockwave/cabs/flash/swflash.cab#version=6,0,29,0'"); 
		sb.append("   width='").append(width).append("' height='").append(height).append("'> ");
		sb.append("  <param name='movie' value='").append(filePath).append("'>");
		sb.append("  <param name='quality' value='high'>                               ");
		sb.append("  <embed src=' ' quality='high'                      ");
		sb.append("  pluginspage='http://www.macromedia.com/go/getflashplayer'         ");
		sb.append("  type='application/x-shockwave-flash' width='227' height='187'>    ");
		sb.append("  </embed>      ");
		sb.append("</object>       ");
		pageContext.getOut().println(sb);
//		if(ad.getHits()==null)
//			ad.setHits(new Integer(1));
//		else
//			ad.setHits( new Integer(ad.getHits().intValue()+1) );
//		if(ad.getShownumber()==null)
//			ad.setShownumber(new Integer(1));
//		else
//			ad.setShownumber( new Integer(ad.getShownumber().intValue()+1) );
//		new ADBlogic().saveAD(ad);
	}
	
	/**
	 * 输出图片广告
	 * @param ad
	 * @throws IOException 
	 */
	private void outputImg(AD ad) throws IOException{
		String filePath = "/AD/"+ ad.getAdtype().getMark()+"/"+ad.getFileurl();
		StringBuffer sb = new StringBuffer();
		sb.append("<img src='").append(filePath).append("' ");
		if(width != null && !width.equals(""))
			sb.append(" width='").append(width).append("'");
		if(height != null && !height.equals(""))
			sb.append(" height='").append(height).append("'");
		if(ad.getMemo() != null && !ad.getMemo().equals(""))
			sb.append(" alt='").append(ad.getMemo()).append("'");
		if(ad.getLink() != null && !ad.getLink().equals("")){
			System.out.println("adlink="+ad.getLink());
			sb.append(" onclick=\"window.open('/fileOutServlet?CMD=openADLink&id=")
			.append(ad.getId()).append("')\"");
			sb.append(" style='cursor:hand'");
		}
//		if(ad.getShownumber()==null)
//			ad.setShownumber(new Integer(1));
//		else
//			ad.setShownumber( new Integer(ad.getShownumber().intValue()+1) );
		sb.append(" >");
		pageContext.getOut().println(sb);
	}
	
	private void outputDefaultImg(String typeMark) throws IOException{
		String filePath = "/AD/"+ typeMark +"/_default.jpg";
		if(new File (filePath).exists()==false){
			filePath = "/AD/_default.jpg";
		}
		StringBuffer sb = new StringBuffer();
		sb.append("<img src='").append(filePath).append("' ");
		if(width != null && !width.equals(""))
			sb.append(" width='").append(width).append("'");
		if(height != null && !height.equals(""))
			sb.append(" height='").append(height).append("'");
		
		sb.append(" >");
		pageContext.getOut().println(sb);
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}


	public String getIndex() {
		return index;
	}


	public void setIndex(String index) {
		this.index = index;
	}


	public String getLanguage() {
		return language;
	}


	public void setLanguage(String language) {
		this.language = language;
	}


	public String getType() {
		return type;
	}


	public void setType(String type) {
		this.type = type;
	}

	public String getHeight() {
		return height;
	}

	public void setHeight(String height) {
		this.height = height;
	}

	public String getWidth() {
		return width;
	}

	public void setWidth(String width) {
		this.width = width;
	}

}
